package utils

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/threading"
	"mzpd_server/internal/svc"
	"mzpd_server/internal/types"
	"strconv"
	"strings"
)

type CommonUtils struct {
	Ctx        context.Context
	serviceCtx *svc.ServiceContext
}

func (c *CommonUtils) placeholders(n int) string {
	var b strings.Builder
	for i := 0; i < n-1; i++ {
		b.WriteString("?,")
	}
	if n > 0 {
		b.WriteString("?")
	}
	return b.String()
}

// PushStatusChanged 推送状态变化
func (c *CommonUtils) PushStatusChanged(groupId int64, registerId string) {
	threading.GoSafe(func() {
		mqUtils := GetMqttServer()
		if !mqUtils.IsRun {
			logx.Errorf("【MQ服务】未启动,推送失败： %s,s%", groupId, registerId)
			return
		}
		p, err := c.serviceCtx.PlayerQueuesModel.FindQueuesContainerGroupsByRegNo(context.Background(), registerId)
		if err != nil {
			logx.Errorf("【MQ服务】获取信息失败： %s", registerId)
			return
		}
		if p == nil {
			logx.Errorf("【MQ服务】未获取到信息： %s", registerId)
			return
		}
		var list = make([]*types.PlayerQueuesGroup, 1)
		list[0] = &types.PlayerQueuesGroup{
			Id:           p.Id,
			Playercode:   p.Playercode.String,
			Patientid:    p.Patientid.String,
			Patientname:  p.Patientname.String,
			Seq:          p.Seq.String,
			Serialnumber: p.Serialnumber.String,
			Deptid:       p.Deptid.String,
			Deptname:     p.Deptname.String,
			Roomid:       p.Roomid.String,
			Roomname:     p.Roomname.String,
			Doctorid:     p.Doctorid.String,
			Doctorname:   p.Doctorname.String,
			State:        p.State.Int64,
			Statelist:    p.Statelist.String,
			Createtime:   p.Createtime.String,
			Groupid:      p.Groupid.Int64,
			Groupname:    p.Groupname.String,
		}
		topic := fmt.Sprintf(`queueChanged/%v`, groupId)
		marshal, _ := json.Marshal(list)
		payload := string(marshal)
		var payLoadObj = &MqttMessage{Msg: payload}
		bytes, _ := json.Marshal(payLoadObj)
		mqUtils.PublishHandler(topic, 2, false, string(bytes))
	})
}

// PushQueues 推送对应状态的数据
func (c *CommonUtils) PushQueues(ids map[int64]int64) {
	//if !GetMqttServer().IsRun {
	//	return
	//}
	threading.GoSafe(func() {
		gIds := make([]int64, 0)
		for _, i2 := range ids {
			gIds = append(gIds, i2)
		}
		if gIds == nil || len(gIds) == 0 {
			return
		}
		var v2 = make([]interface{}, len(gIds))
		for i, val := range gIds {
			v2[i] = val
		}
		datas, err := c.serviceCtx.PlayerQueuesModel.FindQueuesContainerGroupsByGroupId(context.Background(), v2)

		if err != nil {
			logx.Errorf("查询分组队列信息失败： %s", err.Error())
			return
		}
		var result = make(map[int64][]*types.PlayerQueuesGroup)
		for _, group := range datas {
			var sList = result[group.Groupid.Int64]
			if sList == nil {
				sList = make([]*types.PlayerQueuesGroup, 0)
			}
			n, e := strconv.ParseFloat(group.Wiget.String, 64)
			if e != nil {
				n = 0
			}
			var info = &types.PlayerQueuesGroup{
				Id:           group.Id,
				Playercode:   group.Playercode.String,
				Patientid:    group.Patientid.String,
				Patientname:  group.Patientname.String,
				Seq:          group.Seq.String,
				Serialnumber: group.Serialnumber.String,
				Deptid:       group.Deptid.String,
				Deptname:     group.Deptname.String,
				Roomid:       group.Roomid.String,
				Roomname:     group.Roomname.String,
				Doctorid:     group.Doctorid.String,
				Doctorname:   group.Doctorname.String,
				State:        group.State.Int64,
				Statelist:    group.Statelist.String,
				Createtime:   group.Createtime.String,
				Groupid:      group.Groupid.Int64,
				Groupname:    group.Groupname.String,
				Sort:         group.Sort.Int64,
				Wiget:        n,
				Starttime:    group.Starttime.String,
				Endtime:      group.Endtime.String,
			}
			sList = append(sList, info)
			result[group.Groupid.Int64] = sList
		}
		for gId, list := range result {
			marshal, _ := json.Marshal(list)
			payload := string(marshal)
			var payLoadObj = &MqttMessage{Msg: payload}
			bytes, _ := json.Marshal(payLoadObj)
			topic := fmt.Sprintf(`queueChanged/%v`, gId)
			GetMqttServer().PublishHandler(topic, 2, false, string(bytes))
		}
	})

}
